package com.link.play.fit.ai.utils

import android.animation.ValueAnimator
import android.widget.TextView
import java.text.DecimalFormat

object NumberAnimator {

    // 默认动画时长 800ms
    fun animateNumberChange(
        textView: TextView,
        start: Number,
        end: Number,
        duration: Long = 800,
        format: String = "0" // 默认整数格式，小数用 "0.00"
    ) {
        // 过滤相同数值
        if (start == end) return

        // 停止之前的动画
        textView.tag?.let {
            if (it is ValueAnimator && it.isRunning) {
                it.cancel()
            }
        }

        val animator = ValueAnimator.ofFloat(start.toFloat(), end.toFloat()).apply {
            this.duration = duration
            addUpdateListener { animation ->
                val currentValue = animation.animatedValue as Float
                // 格式化数字
                val formattedValue = DecimalFormat(format).format(currentValue)
                textView.text = formattedValue
            }
        }
        textView.tag = animator
        animator.start()
    }
}
